import sys
import os
import subprocess
from time import time

from pyTQDist import *

NUMBER_OF_REPEATS = 10

def runCmd(cmdLine, cwd='.'):
    sb = subprocess.Popen([cmdLine], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, cwd = cwd)
    (result, ignore) = sb.communicate()
    return (sb.returncode, result.strip())


def make_tree(n, d):
    commandLine = "./treeGen 1 %d %d" % (n, d)
    (returnCode, result) = runCmd(commandLine)
    if returnCode != 0:
        print result;
        sys.exit(-1)
    tree = (result.split())[-1]
    # print tree
    return tree


if __name__ == "__main__":
    # read commandline parameters
    if(len(sys.argv) != 3):
        print "Usage:", sys.argv[0], " <number of leafs> <degree>"
        exit(-1)

    n = int(sys.argv[1])
    d = int(sys.argv[2])

    tqDistTimes = []
    qdistTimes = []
    for i in xrange(NUMBER_OF_REPEATS):
        tree1 = make_tree(n, d)
        filename1 = "trees/tree_%d_%d_%d_1.new" % (n, d, i)
        with open(filename1, 'w') as f:
            f.write(tree1)

        tree2 = make_tree(n, d)
        filename2 = "trees/tree_%d_%d_%d_2.new" % (n, d, i)
        with open(filename2, 'w') as f:
            f.write(tree2)

        start = time()
        result = quartetDistance(filename1, filename2)
        stop = time()
        # print "tqDist result:", result
        tqDistTimes.append(stop - start)

        start = time()
        (resultCode, result) = runCmd("./qdist_gen %s %s" % (filename1, filename2))
        stop = time()
        if(resultCode != 0):
            print "resultCode:" , resultCode
            print result
            sys.exit(-1)
        # print "qdist result:", result
        qdistTimes.append(stop-start)

    print n, d, sum(tqDistTimes)/len(tqDistTimes), sum(qdistTimes)/len(qdistTimes) 
